package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.security.Permissions;
import java.util.*;

/**
 * @author L5775
 */
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void save(Permission permission) {
        //检查参数合法性
        //假设业务很复杂
        permissionMapper.insert(permission);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult<Permission> query(QueryObject qo) {
        int count = permissionMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count, Collections.emptyList());
        }
        //判断当前页是否大于总页数
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize()
                : count / qo.getPageSize() + 1;
        if (qo.getCurrentPage()>totalPage){
            //如果大于就设置当前页为最后一页
            qo.setCurrentPage(totalPage);
        }

        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,permissions);
    }
    @Autowired
    ApplicationContext ctx;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public void reload() { //方法目的,不想手动一条条添加到数据库,想用程序自动批量处理
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        //所有贴了@RequestMapping注解的方法
        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod method : values) {
            RequirePermission annotation = method.getMethodAnnotation(RequirePermission.class);
        }
        //查询数据库中所有权限表达式
        List<Permission> permissions = permissionMapper.selectAll();
        ArrayList<String> list = new ArrayList<>();
        for (Permission p : permissions) {
            list.add(p.getExpression());
        }
        //1.获取所有的controller(数组)
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beans.values();
        //2.获取controller(单个)
        for (Object controller : controllers) {
            //3.获取controller中的方法(数组)
            Method[] methods = controller.getClass().getDeclaredMethods();
            //4.遍历数组获取每个方法(单个)
            for (Method method : methods) {
                //5.判断该方法是否有贴自定义的权限注解
                RequirePermission requirePermission = method.getAnnotation(RequirePermission.class);
                if (requirePermission==null){
                    //没贴 跳过
                    continue;
                }
                //有贴
                //6.从该注解中获取name和expression的属性值,封装成一个Permission权限对象
                String name = requirePermission.name();
                String expression = requirePermission.expression();
                //判断该表达式是否已经存在数据库中,如果已经存在则不插入
                if (!list.contains(expression)){
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setExpression(expression);
                    //7.把该权限插入到数据库中
                    permissionMapper.insert(permission);
                }
            }
        }
    }
    @Override
    public List<String> selectByEmpId(Long id) {
        return permissionMapper.selectByEmpId(id);
    }

}
